package view;

import model.*;

import javax.swing.*;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class CustomerView extends JFrame {
    private String username; // 当前登录用户
    private JComboBox<String> storeComboBox;
    private JComboBox<String> itemTypeComboBox;
    private JComboBox<MenuItem> menuItemComboBox;
    private JButton addPizzaButton, placeOrderButton, addItemButton;
    private JCheckBox extraCheeseBox, mushroomsBox, olivesBox, pepperoniBox;
    private JTextField quantityField;
    private JPanel pizzaToppingPanel;

    private int selectedStoreID = -1; // 当前选择的门店ID

    public CustomerView(String username) {
        this.username = (username != null && !username.isEmpty()) ? username : "测试用户"; // 设置用户名
        setTitle("Pizza Ordering System - " + this.username);
        setSize(600, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

        // 添加门店选择下拉框
        panel.add(new JLabel("选择门店:"));
        List<String[]> stores = loadStores();
        List<String> storeNames = new ArrayList<>();
        for (String[] store : stores) {
            storeNames.add(store[1]); // 只加载门店名称
        }

        storeComboBox = new JComboBox<>(storeNames.toArray(new String[0]));
        storeComboBox.addActionListener(e -> onStoreSelected(stores));
        panel.add(storeComboBox);

        // 添加餐点类型选择下拉框
        panel.add(new JLabel("选择餐点类型:"));
        itemTypeComboBox = new JComboBox<>();
        itemTypeComboBox.addActionListener(e -> loadMenuItems());
        panel.add(itemTypeComboBox);

        // 添加餐点选择下拉框
        panel.add(new JLabel("选择餐点:"));
        menuItemComboBox = new JComboBox<>();
        panel.add(menuItemComboBox);

        // 配料选项（仅用于披萨）
        pizzaToppingPanel = new JPanel();
        pizzaToppingPanel.setLayout(new BoxLayout(pizzaToppingPanel, BoxLayout.Y_AXIS));
        pizzaToppingPanel.add(new JLabel("选择披萨配料:"));
        extraCheeseBox = new JCheckBox("额外芝士");
        mushroomsBox = new JCheckBox("蘑菇");
        olivesBox = new JCheckBox("橄榄");
        pepperoniBox = new JCheckBox("意大利香肠");
        pizzaToppingPanel.add(extraCheeseBox);
        pizzaToppingPanel.add(mushroomsBox);
        pizzaToppingPanel.add(olivesBox);
        pizzaToppingPanel.add(pepperoniBox);
        panel.add(pizzaToppingPanel);

        // 数量输入
        panel.add(new JLabel("输入数量:"));
        quantityField = new JTextField(5);
        panel.add(quantityField);

        // 按钮
        addPizzaButton = new JButton("添加披萨");
        addItemButton = new JButton("添加其他餐点");
        placeOrderButton = new JButton("下单");
        panel.add(addPizzaButton);
        panel.add(addItemButton);
        panel.add(placeOrderButton);

        add(panel);

        // 创建订单对象
        Order order = new Order(0, this.username, selectedStoreID, null, 0);
        if (!stores.isEmpty()) {
            selectedStoreID = Integer.parseInt(stores.get(0)[0]);
            loadItemTypes(); // 加载餐点类型
            loadMenuItems(); // 加载默认菜单项
        }
        // 添加披萨按钮功能
        addPizzaButton.addActionListener(e -> {
            try {
                // 验证餐点类型是否为披萨
                if (!"Pizza".equals(itemTypeComboBox.getSelectedItem())) {
                    JOptionPane.showMessageDialog(null, "当前选择的餐点类型不是披萨！");
                    return;
                }

                // 获取数量并验证
                int quantity = Integer.parseInt(quantityField.getText());
                if (quantity <= 0) {
                    JOptionPane.showMessageDialog(null, "数量必须大于0！");
                    return;
                }

                // 计算披萨的总价格（基础价格 + 配料价格）
                double basePrice = 10.0; // 假设披萨的基础价格
                StringBuilder description = new StringBuilder("披萨 (基础价格: $10.0");
                if (extraCheeseBox.isSelected()) {
                    basePrice += 2.0;
                    description.append(", 额外芝士: $2.0");
                }
                if (mushroomsBox.isSelected()) {
                    basePrice += 1.5;
                    description.append(", 蘑菇: $1.5");
                }
                if (olivesBox.isSelected()) {
                    basePrice += 1.0;
                    description.append(", 橄榄: $1.0");
                }
                if (pepperoniBox.isSelected()) {
                    basePrice += 2.5;
                    description.append(", 意大利香肠: $2.5");
                }
                description.append(")");

                // 创建披萨的菜单项并添加到订单
                MenuItem pizzaItem = new MenuItem(0, selectedStoreID, description.toString(), "Pizza", basePrice);
                order.addOrderDetail(new OrderDetail(pizzaItem, quantity));

                // 显示成功提示
                JOptionPane.showMessageDialog(null, "已成功添加披萨: " + description + " 数量: " + quantity);
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "数量必须是数字！");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "添加披萨失败: " + ex.getMessage());
            }
        });

// 添加其他餐点按钮功能
        addItemButton.addActionListener(e -> {
            try {
                // 验证输入的数量是否为正整数
                int quantity = Integer.parseInt(quantityField.getText());
                if (quantity <= 0) {
                    JOptionPane.showMessageDialog(null, "数量必须大于0！");
                    return;
                }

                // 从菜单项选择框中获取当前选中的餐点
                MenuItem selectedItem = (MenuItem) menuItemComboBox.getSelectedItem();
                if (selectedItem == null) {
                    JOptionPane.showMessageDialog(null, "请选择一个餐点！");
                    return;
                }

                // 将选中的餐点添加到订单中
                OrderDetail itemDetail = new OrderDetail(selectedItem, quantity);
                order.addOrderDetail(itemDetail);

                // 提示用户添加成功
                JOptionPane.showMessageDialog(null, "已成功添加餐点: " + selectedItem.getItemName() + " 数量: " + quantity);
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(null, "数量必须是数字！");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "添加餐点失败: " + ex.getMessage());
            }
        });




        // 下单按钮功能
        placeOrderButton.addActionListener(e -> {
            try {
                if (order.getOrderDetails().isEmpty()) {
                    JOptionPane.showMessageDialog(null, "订单中没有任何物品，请添加物品后再下单！");
                    return;
                }

                // 确保 StoreID 合法
                if (selectedStoreID <= 0) {
                    JOptionPane.showMessageDialog(null, "未选择合法的门店！");
                    return;
                }
                // 设置订单的 StoreID
                order.setStoreID(selectedStoreID);

                // 创建订单数据访问对象
                OrderDAO orderDAO = new OrderDAO();

                // 更新订单总金额
                order.updateTotalPrice();

                // 保存订单到数据库
                orderDAO.saveOrder(order);

                // 提示订单提交成功
                JOptionPane.showMessageDialog(null, "订单已成功提交！订单总金额: $" + order.getTotalCost());
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "下单失败: " + ex.getMessage());
            }
        });

    }

    private List<String[]> loadStores() {
        List<String[]> stores = new ArrayList<>();
        try (Connection connection = DatabaseConnection.getConnection()) {
            String query = "SELECT StoreID, StoreName FROM Stores";
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(query);

            while (resultSet.next()) {
                stores.add(new String[]{
                        resultSet.getString("StoreID"),
                        resultSet.getString("StoreName")
                });
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载门店失败: " + e.getMessage());
        }
        return stores;
    }

    private void onStoreSelected(List<String[]> stores) {
        int selectedIndex = storeComboBox.getSelectedIndex();
        if (selectedIndex >= 0) {
            selectedStoreID = Integer.parseInt(stores.get(selectedIndex)[0]);
            loadItemTypes();
        }
    }

    private void loadItemTypes() {
        try {
            MenuItemDAO menuItemDAO = new MenuItemDAO();
            List<MenuItem> items = menuItemDAO.getMenuItemsByStoreID(selectedStoreID);

            itemTypeComboBox.removeAllItems();
            for (MenuItem item : items) {
                if (!isItemTypeExists(item.getItemType())) {
                    itemTypeComboBox.addItem(item.getItemType());
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载餐点类型失败: " + e.getMessage());
        }
    }


    private void loadMenuItems() {
        try {
            MenuItemDAO menuItemDAO = new MenuItemDAO();
            String selectedType = (String) itemTypeComboBox.getSelectedItem();
            List<MenuItem> items = menuItemDAO.getMenuItemsByTypeAndStore(selectedStoreID, selectedType);

            menuItemComboBox.removeAllItems();
            for (MenuItem item : items) {
                menuItemComboBox.addItem(item);
            }

            // 配料面板仅在选择披萨时显示
            pizzaToppingPanel.setVisible("Pizza".equals(selectedType));
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载菜单失败: " + e.getMessage());
        }
    }


    private boolean isItemTypeExists(String type) {
        for (int i = 0; i < itemTypeComboBox.getItemCount(); i++) {
            if (itemTypeComboBox.getItemAt(i).equals(type)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new CustomerView("测试用户").setVisible(true));
    }
}
